package com.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

//脏话过滤器
public class DirtyFilter implements Filter {
	
	private static  List<String> list = new ArrayList<String>() ;
	
	static{
		list.add("狗日") ;
		list.add("畜生") ;
	}

	public void init(FilterConfig filterConfig) throws ServletException {

	}
	public void destroy() {

	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		// 将请求和响应转换为与协议相关的请求和响应
		HttpServletRequest request;
		HttpServletResponse response;
		try {
			request = (HttpServletRequest) req;
			response = (HttpServletResponse) res;
		} catch (ClassCastException e) {
			throw new ServletException("non-HTTP request or response");
		}
		
		MyHttpServletRequest myreq = new MyHttpServletRequest(request) ;
		
		chain.doFilter(myreq, response) ;
	}

	

	class MyHttpServletRequest extends HttpServletRequestWrapper {

		private HttpServletRequest request;

		public MyHttpServletRequest(HttpServletRequest request) {
			super(request);
			this.request = request;
		}

		@Override
		public String getParameter(String name) {
			//由于发言中有脏话，所以需要过滤，首先拿到原始的数据
			String  data = request.getParameter(name) ;
			
			//过滤
			for (String  s : list) {
				if(data.contains(s)){
					data = data.replaceAll(s, "***") ;
				}
			}
			return data;
		}

	}

}
